package com.dongrj.framework.starter.sms.client;

import com.dongrj.framework.starter.sms.SmsRequest;
import com.dongrj.framework.starter.sms.SmsResponse;
import com.dongrj.framework.starter.sms.enums.SmsEnum;
import com.dongrj.framework.starter.sms.properties.TencentYunSmsProperties;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class TencentYunSmsClient extends AbstractSmsClient {
    private final SmsClient client;
    private final TencentYunSmsProperties tencentYunSmsProperties;

    public TencentYunSmsClient(TencentYunSmsProperties tencentYunSmsProperties) {
        this.tencentYunSmsProperties = tencentYunSmsProperties;
        Credential cred = new Credential(tencentYunSmsProperties.secretId, tencentYunSmsProperties.getSecretKey());
        this.client = new SmsClient(cred, "ap-shanghai");
    }

    @Override
    public SmsResponse doSend(SmsRequest smsRequest) {
        SendSmsRequest sendSmsRequest = toSendSmsRequest(smsRequest);
        SmsResponse smsResponse = new SmsResponse();
        smsResponse.setCode(0);
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = this.client.SendSms(sendSmsRequest);
        } catch (TencentCloudSDKException e) {
            log.info("doSend.smsRequest={}", smsRequest);
            log.error("doSend.e", e);
        }
        if (Objects.isNull(sendSmsResponse)) {
            return smsResponse;
        }
        SendStatus[] sendStatusSet = sendSmsResponse.getSendStatusSet();
        List<SendStatus> failItems = Arrays.stream(sendStatusSet).filter(item -> notEquals(item.getCode(), "Ok")).collect(Collectors.toList());
        if (size(failItems) == 0) {
            smsResponse.setCode(1);
            return smsResponse;
        }
        log.info("doSend.failItems={}", failItems);
        return smsResponse;
    }

    public SendSmsRequest toSendSmsRequest(SmsRequest smsRequest) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppId(this.tencentYunSmsProperties.getSdkAppId());
        sendSmsRequest.setSignName(this.tencentYunSmsProperties.getSignName());
        sendSmsRequest.setTemplateId(smsRequest.getTemplateCode());
        sendSmsRequest.setTemplateParamSet(null);
        List<String> strings = mobileToList(smsRequest.getMobiles());
        sendSmsRequest.setPhoneNumberSet(strings.toArray(new String[0]));
        return sendSmsRequest;
    }

    @Override
    public SmsEnum smsEnum() {
        return SmsEnum.Tencent;
    }
}
